import { App, Button, Flex, Form, Popconfirm, Space, Table } from "antd";
import type { TableProps } from "antd";
import { useEffect, useState } from "react";
import { EditUser } from "./EditUser";
import { DataType } from "./types";
import { AddUser } from "./AddUser";
// import { produce } from "immer";
import { createUser, getUserList, deleteUser, updateUser } from "@/api/userApi";
import { produce } from "immer";
import { DeleteOutlined, EditOutlined } from "@ant-design/icons";

const roleMap = {
  0: "超级管理员",
  1: "普通用户",
};

export const User = () => {
  const columns: TableProps<DataType>["columns"] = [
    {
      title: "名字",
      dataIndex: "username",
      key: "username",
      render: (text) => <a>{text}</a>,
    },

    {
      title: "角色",
      dataIndex: "roleId",
      key: "roleId",
      render: (text) => roleMap[text as keyof typeof roleMap],
    },

    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => editUser(record)}>
            <EditOutlined />
            编辑
          </a>
          <Popconfirm
            title="确定删除此用户吗?"
            onConfirm={() => handleDeleteUser(record)} // 用户确认删除时执行
            okText="是"
            cancelText="否"
          >
            <a style={{ color: "red" }}>
              <DeleteOutlined /> 删除
            </a>
          </Popconfirm>
        </Space>
      ),
    },
  ];
  const [data, setData] = useState<DataType[]>([]);

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [currentUser, setCurrentUser] = useState<DataType | null>(null);
  const [form] = Form.useForm();
  const [isAddModalOpen, setIsAddModalOpen] = useState(false);
  const [addForm] = Form.useForm();

  const { message } = App.useApp();

  useEffect(() => {
    const fetchData = async () => {
      try {
        const getUserResult = await getUserList();
        const res = getUserResult.data.map((item) => {
          return {
            key: item.id,
            ...item,
          };
        });
        setData(res);
        console.log("res", res);
      } catch (error: any) {
        console.error("请求失败", error);
        message.error(error.message);
      }
    };
    fetchData();
  }, []);

  const editUser = (record: DataType) => {
    setCurrentUser(record);
    form.setFieldsValue(record);
    setIsModalOpen(true);
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      console.log("values", values);

      const updateUserResult = await updateUser(currentUser!.key, values);
      if (updateUserResult.success) {
        setData(
          produce(data, (draft) => {
            const index = draft.findIndex((item) => item.key === currentUser?.key);
            if (index !== -1) {
              draft[index] = { ...draft[index], ...values };
            }
          })
        );
        setIsModalOpen(false);

        message.success("用户信息更新成功");
      } else {
        message.error(updateUserResult.message);
      }
    } catch (error) {
      console.error("验证失败:", error);
    }
  };

  const handleAdd = async () => {
    try {
      const values = await addForm.validateFields();
      const newUser = {
        ...values,
      };

      const createUserResult = await createUser({
        username: newUser.username,
        password: newUser.password,
        roleId: newUser.roleId,
      }).catch((error) =>
        Promise.resolve({
          success: false,
          message: error.message,
          data: {
            id: null,
          },
        })
      );
      if (createUserResult.success) {
        newUser.key = createUserResult.data.id;
        setData([...data, newUser]);
        setIsAddModalOpen(false);
        addForm.resetFields();
        message.success("添加用户成功");
      } else {
        message.error(createUserResult.message);
      }
    } catch (error) {
      console.error("验证失败:", error);
    }
  };

  const handleDeleteUser = async (record: DataType) => {
    console.log(record);

    const deleteUserResult = await deleteUser(record.key);
    console.log("deleteUserResult", deleteUserResult);
    if (deleteUserResult.success) {
      message.success("删除用户成功");
      setData(data.filter((item) => item.key !== record.key));
      const newData = produce(data, (draft) => {
        const index = draft.findIndex((item) => item.key === record.key);
        if (index !== -1) {
          draft.splice(index, 1);
        }
      });
      setData(newData);
    } else {
      message.error(deleteUserResult.message);
    }
  };

  return (
    <div className="p-[12px]">
      <Flex gap="middle" vertical>
        <Flex align="center" gap="middle">
          <Button>刷新</Button>
          <Button type="primary" onClick={() => setIsAddModalOpen(true)}>
            添加
          </Button>
        </Flex>
        <Table<DataType>
          columns={columns}
          dataSource={data}
          bordered
          locale={{
            emptyText: "暂无数据",
          }}
        ></Table>
      </Flex>

      <EditUser
        isModalOpen={isModalOpen}
        handleOk={handleOk}
        onCancel={() => setIsModalOpen(false)}
        form={form}
        currentUser={currentUser}
      />

      <AddUser
        isModalOpen={isAddModalOpen}
        handleOk={handleAdd}
        onCancel={() => setIsAddModalOpen(false)}
        form={addForm}
      />
    </div>
  );
};
